Ext.define('YXMES.smfr.controller.WorkOrderInputMaterialController', {
	extend : 'Ext.app.Controller',
	refs : [ {
		selector : 'smfr_workorderinputmaterial',
		ref : 'smfrworkorderinputmaterial'
	} ],
	requires : [ 'YXMES.smfr.store.WorkOrderNeetMatStore', 'YXMES.smfr.store.WorkOrderStore', 'YXMES.smfr.store.MoPsnStore' ],
	stores : [],
	models : [],
	views : [ 'YXMES.smfr.view.WorkOrderInputMaterialView' ],
	subcontrollers : [  ],
	_init : false,
	init : function() {
		if (this._init)
			return;
		this._init = true;
		this.control({
			'smfr_workorderinputmaterial' : {
				afterrender : function() {
					return this.handle(this.onAfterrender, arguments);
				},
				destroy : function() {
					return this.handle(this.onDestroy, arguments);
				}
			},
			'smfr_workorderinputmaterial #txtResBarcode' : {
				specialkey : function() {
					return this.handle(this.onTxtResBarcodeSpecialkey, arguments);
				}
			},
			'smfr_workorderinputmaterial #cdvMo' : {
				specialkey : function() {
					return this.handle(this.onCdvMoSpecialkey, arguments);
				},
				select : function() {
					return this.handle(this.onCdvMoSelect, arguments);
				}
			},
			'smfr_workorderinputmaterial #numInputQty' : {
				specialkey : function() {
					return this.handle(this.onNumInputQtySpecialkey, arguments);
				}
			},
			'smfr_workorderinputmaterial #txtMsn' : {
				specialkey : function() {
					return this.handle(this.onTxtMsnSpecialkey, arguments);
				}
			},
			'smfr_workorderinputmaterial #btnSave' : {
				click : function() {
					return this.handle(this.onBtnSaveClick, arguments);
				}
			},
			'smfr_workorderinputmaterial #btnPrint' : {
				click : function() {
					return this.handle(this.onBtnPrintClick, arguments);
				}
			},
			'smfr_workorderinputmaterial #txtSearchMo' : {
				specialkey : function() {
					return this.handle(this.onTxtSearchMoSpecialkey, arguments);
				}
			}
		});
		if (!Ext.isEmpty(this.subcontrollers)) {
			Ext.each(this.subcontrollers, function(name) {
				this.getController(name).init();
			}, this);
		}
		// User definied init
	},
	mainView : undefined,
	getMainView : function() {
		return this.mainView;
	},
	getScopeView : function() {
		return this.getMainView().scopeView || {};
	},
	getInput : function() {
		return this.getScopeView().input || {};
	},
	setInput : function(data) {
		this.getMainView().input = data;
	},
	getOutput : function() {
		return this.getMainView().output || {};
	},
	setOutput : function(data) {
		this.getScopeView().output = data;
	},
	handle : function(func, args) {
		var item = args && args.length > 0 && Ext.typeOf(args[0]) === 'object' ? args[0] : undefined;
		if (item) {
			try {
				this.mainView = (item.xtype == 'smfr_workorderinputmaterial' ? item : item.up('smfr_workorderinputmaterial'));
			} catch(e) {
			}
		}
		try {
			return func.apply(this, args);
		} finally {
		}
	},
	getItem : function(itemId) {
		return itemId===this.getMainView().getItemId()?this.getMainView():this.getMainView().down('#' + itemId);
	},
	getStore : function(name) {
		if (name == 'WorkOrderNeetMatStore')
			return this.getMainView().SmfrViewWorkOrderNeedInputMaterialServiceStore;
		if (name == 'InputMoScanResultStore')
			return this.getMainView().inputMoScanResultStoreStore;
		if (name == 'WorkOrderStore')
			return this.getMainView().SmfrViewProductionOrderServiceStore;
		if (name == 'MoPsnStore')
			return this.getMainView().SmfrViewProductionSnServiceStore;
		return undefined;
	},
	bind : function(view) {
		view = (view ? view : this.getMainView());
		view.SmfrViewWorkOrderNeedInputMaterialServiceStore = Ext.create('YXMES.smfr.store.WorkOrderNeetMatStore', {
			pageSize : 30
		});
		view.inputMoScanResultStoreStore = Ext.create('Ext.data.ArrayStore', {
			pageSize : 30,
			fields : [ {
				name : 'mo',
				type : 'string'
			}, {
				name : 'resBarcode',
				type : 'string'
			}, {
				name : 'inputQty',
				type : 'string'
			}, {
				name : 'msn',
				type : 'string'
			}, {
				name : 'scanTime',
				type : 'string'
			}, {
				name : 'matCode',
				type : 'string'
			}, {
				name : 'matDesc',
				type : 'string'
			} ]
		});
		view.SmfrViewProductionOrderServiceStore = Ext.create('YXMES.smfr.store.WorkOrderStore', {
			pageSize : 30
		});
		view.SmfrViewProductionSnServiceStore = Ext.create('YXMES.smfr.store.MoPsnStore', {
			pageSize : 30
		});
		view.down('#grdBom').reconfigure(view.SmfrViewWorkOrderNeedInputMaterialServiceStore);
		view.down('#grdInput').reconfigure(view.inputMoScanResultStoreStore);
		view.down('#cdvMo').bindStore(view.SmfrViewProductionOrderServiceStore);
		view.down('#grdPsn').reconfigure(view.SmfrViewProductionSnServiceStore);
	},
	onAfterrender : function(view, eOpts) {
		this.bind();
		// User defined afterrender
	},
	onDestroy : function(view, eOpts) {
		// User defined destory
		var view = this.getMainView();
		if (view.SmfrViewWorkOrderNeedInputMaterialServiceStore) {
			view.SmfrViewWorkOrderNeedInputMaterialServiceStore.destroyStore();
			view.SmfrViewWorkOrderNeedInputMaterialServiceStore = undefined;
		}
		if (view.inputMoScanResultStoreStore) {
			view.inputMoScanResultStoreStore.destroyStore();
			view.inputMoScanResultStoreStore = undefined;
		}
		if (view.SmfrViewProductionOrderServiceStore) {
			view.SmfrViewProductionOrderServiceStore.destroyStore();
			view.SmfrViewProductionOrderServiceStore = undefined;
		}
		if (view.SmfrViewProductionSnServiceStore) {
			view.SmfrViewProductionSnServiceStore.destroyStore();
			view.SmfrViewProductionSnServiceStore = undefined;
		}
		if (this.getMainView().input)
			this.getMainView().input = undefined;
		if (this.getMainView().output)
			this.getMainView().output = undefined;
	},
	onTxtResBarcodeSpecialkey : function(textfield, e, eOpts) {
		if (e.getKey() == e.ENTER) {
		    if (this.ignoreInputQty === "Y") {
		        this.getItem('txtMsn').focus(true);
		        return;
		    }
		    this.getItem('numInputQty').focus(true);
		}
	},
	onCdvMoSpecialkey : function(codeviewfieldx, e, eOpts) {
		if (e.getKey() == e.ENTER) {
		    this.loadMoInfo(codeviewfieldx.getValue());
		}
	},
	onCdvMoSelect : function(btn, record) {
		this.loadMoInfo(record.get('mo'));
	},
	onNumInputQtySpecialkey : function(numberfield, e, eOpts) {
		if (e.getKey() == e.ENTER) {
		    this.getItem('txtMsn').focus(true);
		}
	},
	onTxtMsnSpecialkey : function(textfield, e, eOpts) {
		if (e.getKey() == e.ENTER) {
		    var txtMsn = this.getItem('txtMsn');
		    if (!this.getItem('frmScan').isValid()) {
		        txtMsn.focus(true);
		    }
		
		    txtMsn.setReadOnly(true);
		    var vMsn = txtMsn.getValue();
		    var inputStore = this.getItem('grdInput').getStore();
		    if (inputStore.findExact('msn', vMsn) >= 0) {
		        this.getItem('dspInfo').setValue(vMsn + "重复投料，操作失败。");
		
		        txtMsn.setReadOnly(false);
		        txtMsn.setValue('');
		        txtMsn.focus(true);
		        return;
		    }
		
		    var me = this;
		    YX.ZbusRpc.request({
		        module: 'SmfrViewMaterialSnCanInputWorkOrderService',
		        params: {
		            mo: me.getItem('cdvMo').getValue(),
		            msn: vMsn
		        },
		        success: function(rsp) {
		            var rcd = me.getItem('grdBom').getStore().findRecord('matCode', rsp.msnSts.matCode);
		            if (!rcd) {
		                me.getItem('dspInfo').setValue(vMsn + "批次物料不在此工单BOM中。");
		                return;
		            }
		
		            rcd.set('scanFlag', 'Y');
		            inputStore.insert(0, {
		                scanTime: Ext.Date.format(new Date(), "H:i:s"),
		                mo: me.getItem('cdvMo').getValue(),
		                resBarcode: me.getItem('txtResBarcode').getValue(),
		                inputQty: me.ignoreInputQty === "Y" ? rsp.msnSts.qty: me.getItem('numInputQty').getValue(),
		                msn: rsp.msnSts.msn,
		                matCode: rsp.msnSts.matCode,
		                matDesc: rsp.msnSts.matDesc
		            });
		        },
		        callback: function(opt, rspOK, rsp) {
		            if (rspOK) {
		                me.getItem('dspInfo').setValue(rsp.rspDesc);
		                if (!me.ignoreInputQty) {
		                    me.ignoreInputQty = me.getItem('numInputQty').getValue() === null ? "Y": "N";
		                }
		            }
		            txtMsn.setReadOnly(false);
		            txtMsn.setValue('');
		            if (me.ignoreInputQty === "Y") {
		                txtMsn.focus();
		            } else {
		                me.getItem('numInputQty').focus(true);
		            }
		        }
		    });
		}
	},
	onBtnSaveClick : function(button, e, eOpts) {
		var tq = this.getItem('numTotalQty');
		var pq = this.getItem('numPsnQty');
		if (!tq.isValid() || !pq.isValid()) {
		    return;
		}
		
		if (tq.getValue() < pq.getValue()) {
		    pq.markInvalid('每产出数不超能过总数。');
		    return;
		}
		
		var me = this;
		var scanMsnList = [];
		me.getItem('grdInput').getStore().each(function(rcd) {
		    scanMsnList.push({
		        msn: rcd.get('msn'),
		        mo: rcd.get('mo'),
		        matCode: rcd.get('matCode'),
		        qty: rcd.get('inputQty'),
		        carryId: rcd.get('resBarcode')
		    });
		});
		
		if (Ext.isEmpty(scanMsnList)) {
		    Ext.Msg.show({
		        title: T.label.save,
		        msg: '无投料数据',
		        icon: Ext.Msg.ERROR,
		        buttons: Ext.Msg.OK
		    });
		    return;
		}
		
		Ext.Msg.show({
		    title: T.label.save,
		    msg: T.msg.are_you_sure_to_save_data,
		    icon: Ext.Msg.QUESTION,
		    buttons: Ext.Msg.YESNO,
		    fn: function(btnId) {
		        if ('yes' == btnId) {
		            button.setDisabled(true);
		
		            YX.ZbusRpc.request({
		                module: 'SmfrSaveScanMaterialToPsnAndPrintService',
		                showSuccess: true,
		                params: {
		                    printFlag: me.getItem('chkPrint').getValue() ? "Y": "N",
		                    totalQty: tq.getValue(),
		                    outputQty: pq.getValue(),
		                    msnStsList: scanMsnList
		                },
		                success: function(rsp) {
		                    me.getItem('frmScan').getForm().reset();
		                    me.loadMoPsnStore({
		                        mo: scanMsnList[0].mo
		                    });
		
		                    if (me.getItem('chkPrint').getValue() && !Ext.isEmpty(rsp.labelFileName)) {
		                        var mainForm = me.getItem('frmMain');
		                        Ext.create('Ext.window.Window', {
		                            title: '标签打印',
		                            height: mainForm.getHeight() - 50,
		                            width: mainForm.getWidth() - 200,
		                            layout: 'fit',
		                            modal: true,
		                            frame: false,
		                            items: [{
		                                html: '<iframe style="width:100%;height:100%" src="export?download=0&fileName=' + rsp.labelFileName + '"/>'
		                            }]
		                        }).show();
		
		                    }
		                },
		                callback: function() {
		                    button.setDisabled(false);
		                }
		            });
		        }
		    }
		});
	},
	onBtnPrintClick : function(button, e, eOpts) {
		var me = this;
		var vPsns = "";
		var rcds = me.getItem('grdPsn').getSelectionModel().getSelection();
		if (Ext.isEmpty(rcds)) {
		    return;
		}
		
		Ext.each(rcds,
		function(rcd) {
		    vPsns += rcd.get('psn') + ',';
		});
		
		Ext.Msg.show({
		    title: T.label.print,
		    msg: '确定要打印吗？',
		    icon: Ext.Msg.QUESTION,
		    buttons: Ext.Msg.YESNO,
		    fn: function(btnId) {
		        if ('yes' == btnId) {
		            button.setDisabled(true);
		
		            YX.ZbusRpc.request({
		                module: 'SmfrViewProductSnToPrintLabelService',
		                showSuccess: false,
		                params: {
		                    psns: vPsns
		                },
		                success: function(rsp) {
		                    if (!Ext.isEmpty(rsp.fileName)) {
		                        var mainForm = me.getItem('frmMain');
		                        Ext.create('Ext.window.Window', {
		                            title: '标签打印',
		                            height: mainForm.getHeight() - 50,
		                            width: mainForm.getWidth() - 200,
		                            layout: 'fit',
		                            modal: true,
		                            frame: false,
		                            items: [{
		                                html: '<iframe style="width:100%;height:100%" src="export?download=0&fileName=' + rsp.fileName + '"/>'
		                            }]
		                        }).show();
		
		                    }
		                },
		                callback: function() {
		                    button.setDisabled(false);
		                }
		            });
		        }
		    }
		});
	},
	onTxtSearchMoSpecialkey : function(textfield, e, eOpts) {
		if (e.getKey() == e.ENTER) {
		    var vMo = textfield.getValue().trim();
		    if (vMo !== "") {
		        this.loadMoPsnStore({
		            mo: vMo
		        });
		    }
		}
	},
	loadMoInfo : function(pMo) {
		this.getItem('frmScan').getForm().reset();
		
		if (Ext.isEmpty(pMo)) {
		    return;
		}
		this.getItem('cdvMo').setValue(pMo);
		
		var me = this;
		YX.ZbusRpc.request({
		    module: 'SmfrViewProductionOrderService',
		    showSuccess: false,
		    params: {
		        mo: pMo
		    },
		    success: function(rsp) {
		        if (!Ext.isEmpty(rsp.orderList)) {
		            me.getItem('txtMatCode').setValue(rsp.orderList[0].matCode);
		            me.getItem('txtMatDesc').setValue(rsp.orderList[0].matDesc);
		            me.getItem('txtMoQty').setValue(rsp.orderList[0].moQty);
		
		            me.loadWorkOrderNeetMatStore({
		                mo: pMo
		            });
		            me.getItem('grdInput').getStore().removeAll();
		
		            me.getItem('txtResBarcode').focus(true);
		        }
		    }
		});
	},
	loadWorkOrderNeetMatStore : function(params, options) {
		params = Ext.applyIf(params||{}, {
			// Default params
		});
		
		var store = this.getStore('WorkOrderNeetMatStore');
		if(!store) {
			return false;
		}
		
		store.getProxy().extraParams = params;
		if(store.loadPage){
			store.loadPage(1, options);
		}else{
			store.load(options);
		}
	},
	loadInputMoScanResultStore : function(params, options) {
		params = Ext.applyIf(params||{}, {
			// Default params
		});
		
		var store = this.getStore('InputMoScanResultStore');
		if(!store) {
			return false;
		}
		
		store.getProxy().extraParams = params;
		if(store.loadPage){
			store.loadPage(1, options);
		}else{
			store.load(options);
		}
	},
	loadWorkOrderStore : function(params, options) {
		params = Ext.applyIf(params||{}, {
			// Default params
		});
		
		var store = this.getStore('WorkOrderStore');
		if(!store) {
			return false;
		}
		
		store.getProxy().extraParams = params;
		if(store.loadPage){
			store.loadPage(1, options);
		}else{
			store.load(options);
		}
	},
	loadMoPsnStore : function(params, options) {
		params = Ext.applyIf(params||{}, {
			// Default params
		});
		
		var store = this.getStore('MoPsnStore');
		if(!store) {
			return false;
		}
		
		store.getProxy().extraParams = params;
		if(store.loadPage){
			store.loadPage(1, options);
		}else{
			store.load(options);
		}
	}
});